package com.ews.onlineexchange.endpoint;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.enterprise.event.Observes;
import javax.enterprise.event.TransactionPhase;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.ews.onlineexchange.service.qualifier.MessagePushWsEvent;

@ServerEndpoint("/messgaePush/{client-id}")
public class MessagePushWS {

	private static Set userSessions = Collections.synchronizedSet(new HashSet());

	@OnMessage
	public String onMessage(String message, Session session, @PathParam("client-id") String clientId) throws IOException {
			System.out.println(message);
			session.getBasicRemote().sendText(message);
			System.out.println("send message to peer ");
			
		return "message was received by socket  and processed: " + message;
	}

	@OnOpen
	public void onOpen(Session session, @PathParam("client-id") String clientId) {
		System.out.println("pened websocket channel for client " + clientId);
		userSessions.add(session);

//		try {
//			session.getBasicRemote().sendText("good to be in touch");
//		} catch (IOException e) {
//		}
	}

	@OnClose
	public void onClose(Session session, @PathParam("client-id") String clientId) {
		userSessions.remove(session);
	}
	

	public void send(@Observes(during = TransactionPhase.AFTER_COMPLETION) @MessagePushWsEvent String message) throws IOException {
		Iterator<Session> sessions = userSessions.iterator();
		while(sessions.hasNext()) {
			Session session = sessions.next();
			session.getBasicRemote().sendText(message);
		}
		
	}

	
}
